<?php

namespace App\Crontab;

use App\Model\ActivityCouponsModel;
use App\Model\ActivityModel;
use App\Model\ActivityRuleModel;
use App\Model\VestQueueModel;
use EasySwoole\Component\WaitGroup;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Pool\Exception\PoolEmpty;
use Throwable;

class AutoAddActivity extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        return '0 0 * * *';
    }

    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        //定时任务名称
        return '零点创建赛事';
    }

    function run(int $taskId, int $workerIndex)
    {
        // TODO: Implement run() method.
        // 定时任务处理逻辑
        Logger::getInstance()->info('零点创建赛事 开始时间:' . date('Y-m-d H:i:s'));
        try {
            $rules = DbManager::getInstance()->invoke(function ($client) {
                return ActivityRuleModel::invoke($client)->where('is_auto', 1)->all();
            });
        } catch (Exception $e) {
            $rules = [];
        } catch (PoolEmpty $e) {
            $rules = [];
        } catch (Throwable $e) {
            $rules = [];
        }

        if (!count($rules)) {
            return false;
        }

        $res = [];
        $wait = new WaitGroup();
        foreach ($rules as $value) {
            $wait->add();
            go(function () use ($wait, &$res, $value) {
                try {
                    //开启事务
                    DbManager::getInstance()->startTransaction();

                    $activityInsertId = ActivityModel::create()->addActivity($value);

                    if ($value->is_coupons == 1 && $value->coupons_id > 0 && $activityInsertId > 0) {
                        ActivityCouponsModel::create()->data([
                            'activity_id' => $activityInsertId,
                            'coupons_id' => $value->coupons_id,
                            'create_time' => time(),
                            'update_time' => time(),
                        ], false)->save();
                    }

                    if ($value->min_random >= 0 && $value->max_random > 0) {
                        mt_srand();
                        $addTarget = mt_rand($value->min_random, $value->max_random) + 24; // 添加马甲目标数
                    } else {
                        $addTarget = 124; // 添加马甲目标数
                    }

                    $bulkInsertData = [];
                    $addTarget = $addTarget - 24;
                    for ($i = 23; $i > -1; $i--) {
                        mt_srand();
                        $hour = str_pad($i, 2, "0", STR_PAD_LEFT);
                        if ($i == 23) {
                            $minute = str_pad(mt_rand(0, 55), 2, "0", STR_PAD_LEFT);
                        } else {
                            $minute = str_pad(mt_rand(0, 59), 2, "0", STR_PAD_LEFT);
                        }
                        $second = str_pad(mt_rand(0, 59), 2, "0", STR_PAD_LEFT);

                        $temp = 1;
                        $lessMoney = 0;
                        if ($addTarget > 0) {
                            if ($i == 0) {
                                $temp += $addTarget;
                            } else {
                                $maxMoney = floor($addTarget / $i);
                                $lessMoney = mt_rand(0, $maxMoney);
                                $temp += $lessMoney;
                            }
                        }
                        $addTarget -= $lessMoney;

                        $bulkInsertData[$i] = [
                            'activity_id' => $activityInsertId,
                            'vest_enrollment' => $temp,
                            'create_time' => time(),
                            'update_time' => time(),
                            'is_done' => 2,
                            'job_time' => strtotime(date('Y-m-d ' . $hour . ':' . $minute . ':' . $second)),
                        ];
                    }

                    VestQueueModel::create()->saveAll($bulkInsertData, true, false);

                    $res[] = $activityInsertId;
                    $wait->done();
                } catch (Throwable  $e) {
                    // 回滚事务
                    DbManager::getInstance()->rollback();
                    var_dump($e->getMessage());
                } finally {
                    // 提交事务
                    DbManager::getInstance()->commit();
                }
            });
        }

        $wait->wait();

        var_dump($res);

        Logger::getInstance()->info('零点创建赛事 结束时间:' . date('Y-m-d H:i:s'));
        return true;
    }

    function onException(Throwable $throwable, int $taskId, int $workerIndex)
    {
        // TODO: Implement onException() method.
        echo $throwable->getMessage();
    }
}